import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime
import uuid



class CheckinHandler:
    """处理打卡交互的类"""

    def __init__(self, app):
        self.app = app
        self.storage = app.storage
        self.colors = app.colors
        self.style = app.style

    def show_checkin_form(self):
        """显示打卡表单"""
        # 清除现有界面
        for widget in self.app.winfo_children():
            widget.destroy()

        # 主框架
        form_frame = ttk.Frame(self.app, padding=20)
        form_frame.pack(fill=tk.BOTH, expand=True)

        # 返回按钮
        back_btn = ttk.Button(form_frame, text="返回", command=self.app.create_main_frame)
        back_btn.pack(anchor="nw", pady=(0, 10))

        # 标题
        title_label = ttk.Label(form_frame, text="今日打卡", style="Subheader.TLabel")
        title_label.pack(pady=(0, 20), anchor="w")

        # 心情选择
        mood_frame = ttk.LabelFrame(form_frame, text="选择心情", padding=10)
        mood_frame.pack(fill=tk.X, pady=10)

        self.selected_mood = tk.StringVar()

        for i, (mood, icon) in enumerate(zip(self.storage.PRESET_MOODS, self.storage.MOOD_ICONS)):
            mood_radio = ttk.Radiobutton(
                mood_frame,
                text=f"{icon} {mood}",
                variable=self.selected_mood,
                value=mood
            )
            mood_radio.grid(row=i // 3, column=i % 3, padx=10, pady=5, sticky="w")

        # 学习小结
        study_frame = ttk.LabelFrame(form_frame, text="学习小结", padding=10)
        study_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        self.study_summary = tk.Text(study_frame, height=5, wrap=tk.WORD)
        self.study_summary.pack(fill=tk.BOTH, expand=True)

        # 生活感悟
        life_frame = ttk.LabelFrame(form_frame, text="生活感悟 (可选)", padding=10)
        life_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        self.life_notes = tk.Text(life_frame, height=3, wrap=tk.WORD)
        self.life_notes.pack(fill=tk.BOTH, expand=True)

        # 目标关联（如果有目标）
        if self.app.goals:
            goals_frame = ttk.LabelFrame(form_frame, text="关联学习目标", padding=10)
            goals_frame.pack(fill=tk.X, pady=10)

            self.goal_vars = []
            for i, goal in enumerate(self.app.goals):
                var = tk.BooleanVar()
                goal_check = ttk.Checkbutton(
                    goals_frame,
                    text=f"{goal['goal_id']}. {goal['description']} [{goal['status']}]",
                    variable=var
                )
                goal_check.pack(anchor="w", pady=2)
                self.goal_vars.append(var)

        # 提交按钮
        submit_btn = ttk.Button(
            form_frame,
            text="提交打卡",
            command=self.submit_checkin,
            style="TButton"
        )
        self.style.configure("Submit.TButton", background=self.colors["primary"])
        submit_btn.configure(style="Submit.TButton")
        submit_btn.pack(pady=20, fill=tk.X)

    def submit_checkin(self):
        """提交打卡记录"""
        # 获取选择的心情
        mood = self.selected_mood.get()
        if not mood:
            messagebox.showerror("错误", "请选择心情")
            return

        # 获取学习小结
        study_summary = self.study_summary.get("1.0", tk.END).strip()
        if not study_summary:
            messagebox.showerror("错误", "学习小结不能为空")
            return

        # 获取生活感悟
        life_notes = self.life_notes.get("1.0", tk.END).strip()

        # 获取关联的目标
        goal_ids = []
        if self.app.goals:
            for i, var in enumerate(self.goal_vars):
                if var.get():
                    goal_ids.append(self.app.goals[i]["goal_id"])

        # 获取当前日期和时间
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")

        # 生成唯一ID
        log_id = str(uuid.uuid4())

        # 组装打卡记录
        checkin_record = {
            "log_id": log_id,
            "date": date_str,
            "time": time_str,
            "mood": mood,
            "study_summary": study_summary,
            "life_notes": life_notes
        }

        # 添加关联目标
        if goal_ids:
            checkin_record["goal_ids"] = goal_ids

        # 保存记录
        self.storage.save_checkin_to_file(checkin_record)
        self.app.checkins.append(checkin_record)

        # 显示成功消息
        messagebox.showinfo("成功", "打卡成功！")

        # 返回主界面
        self.app.create_main_frame()